package www.wmx.com.xssc.util;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import www.wmx.com.xssc.domain.doc.fj.RbtScfjMb;
import www.wmx.com.xssc.domain.doc.fj.ZtComUploadFile;
import www.wmx.com.xssc.domain.doc.fj.ZtComUploadFileOrigin;
import www.wmx.com.xssc.domain.doc.jcyjj.RbtKjjlJcyjjFjxx;
import www.wmx.com.xssc.domain.doc.jsfmj.RbtKjjlJsfmjFjxx;
import www.wmx.com.xssc.domain.doc.kjjbj.RbtKjjlKjjbjFjxx;
import www.wmx.com.xssc.domain.mb.RbtKjjlMbJcyjRank;
import www.wmx.com.xssc.domain.mb.RbtKjjlMbJcyjj;
import www.wmx.com.xssc.domain.mb.RbtKjjlMbTy;
import www.wmx.com.xssc.domain.vo.WcryShortXM;
import www.wmx.com.xssc.domain.vo.extract.BaseMatchResult;
import www.wmx.com.xssc.domain.vo.extract.ExtractTSecret;
import www.wmx.com.xssc.domain.vo.extract.request.TSecretRequest;
import www.wmx.com.xssc.domain.vo.request.RequestPicture;
import www.wmx.com.xssc.domain.vo.response.ResponsePicture;
import www.wmx.com.xssc.service.fj.IRbtScfjMbService;
import www.wmx.com.xssc.service.fj.IZtComUploadFileOriginService;
import www.wmx.com.xssc.service.fj.IZtComUploadFileService;
import www.wmx.com.xssc.service.jcyjj.IRbtKjjlJcyjjFjxxService;
import www.wmx.com.xssc.service.jcyjj.IRbtKjjlJcyjjJbxxService;
import www.wmx.com.xssc.service.jsfmj.IRbtKjjlJsfmjFjxxService;
import www.wmx.com.xssc.service.kjjbj.IRbtKjjlKjjbjFjxxService;
import www.wmx.com.xssc.util.common.MbReadUtil;
import www.wmx.com.xssc.util.common.NameConvertUtil;
import www.wmx.com.xssc.util.common.WcrReadUtil;
import www.wmx.com.xssc.util.enumUtil.CgType;
import www.wmx.com.xssc.util.enumUtil.CgjlType;
import www.wmx.com.xssc.util.pdf.PDF;
import www.wmx.com.xssc.util.time.DateFormatterUtil;
import www.wmx.com.xssc.util.tptq.ImageExtractionUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static www.wmx.com.xssc.xm.Similarity.pinyinSimilarity;

/**
 * @author Zhenyao.Diao
 * @create 2024/9/29 9:20
 * @description
 */
@Data
@Slf4j
@Component
public class TSecretProcessUtil {
    /**
     * 列举类型所有的成果奖励的基本信息业务类：
     */
    @Resource(description = "基础研究奖的基本信息：")
    private IRbtKjjlJcyjjJbxxService jcyjjJbxxService;

    @Resource
    private MbReadUtil mbReadUtil;
    /**
     * 所有当前年度的项目中涉及的研究人员和项目的信息：
     */
    @Resource
    private WcrReadUtil wcrReadUtil;

    @Resource(description = "附件的类型枚举")
    private IRbtScfjMbService scfjMbService;

    //论文附件的所有的类型和名称：
    List<RbtScfjMb> scfjJcyjjLWMbList;
    List<RbtScfjMb> scfjKjjbjjLWMbList;
    List<RbtScfjMb> scfjJsfmjLWMbList;

    @Resource(description = "基础研究附件信息")
    private IRbtKjjlJcyjjFjxxService jcyjjFjxxService;

    @Resource(description = "技术发明奖附件信息")
    private IRbtKjjlJsfmjFjxxService jsfmjFjxxService;

    @Resource(description = "科技进步奖附件信息")
    private IRbtKjjlKjjbjFjxxService kjjbjFjxxService;

    @Resource
    private IZtComUploadFileService uploadFileService;
    @Resource
    private IZtComUploadFileOriginService uploadFileOriginService;

    @Resource(description = "论文图片提取工具")
    private ImageExtractionUtil imageExtractionUtil;

    // 作者排名：
    private RbtKjjlMbJcyjRank kjjlMbJcyjRank;
    //contains:   0、1、2
    private RbtKjjlMbTy rbtKjjlMbTyLW;
    // 基础研究奖根据等级要求论文的信息：
    private List<RbtKjjlMbJcyjj> kjjlMbJcyjjsList;
    private static final Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private String basePath;

    public void init() {
        this.mbReadUtil.init();
        this.scfjJcyjjLWMbList = scfjMbService.lambdaQuery()
                .eq(RbtScfjMb::getYwlx, "基础研究奖")
                .eq(RbtScfjMb::getWjlx, "获奖证书").list();
        this.scfjKjjbjjLWMbList = scfjMbService.lambdaQuery()
                .eq(RbtScfjMb::getYwlx, "科技进步奖")
                .eq(RbtScfjMb::getWjlx, "获奖证书").list();
        this.scfjJsfmjLWMbList = scfjMbService.lambdaQuery()
                .eq(RbtScfjMb::getYwlx, "技术发明奖")
                .eq(RbtScfjMb::getWjlx, "获奖证书").list();
        this.kjjlMbJcyjRank = this.mbReadUtil.getKjjlMbJcyjRank();
        this.kjjlMbJcyjjsList = this.mbReadUtil.getKjjlMbJcyjjsList();
        List<RbtKjjlMbTy> kjjlMbTyList = this.mbReadUtil.getKjjlMbTyList();
        for (RbtKjjlMbTy mbTy : kjjlMbTyList) {
            if (mbTy.getId().equals(CgType.JSMM.getCode())) {
                this.rbtKjjlMbTyLW = mbTy;
                break;
            }
        }
        try {
            Properties properties = new Properties();
            // 读取my.properties配置文件到输入流中
            InputStream inputStream = PDF.class.getResourceAsStream("/config.properties");
            // 从输入流中加载属性列表
            properties.load(inputStream);
            this.basePath = properties.getProperty("file.upload.path");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取专利相关附件的文件路径
     *
     * @param tSecretRequest
     * @return
     */
    public String getTSecretPath(TSecretRequest tSecretRequest) {
        String path = null;
        String FJID = null;
        if (tSecretRequest.getCgjlType() == CgjlType.JCYJJ.getCode()) {
            RbtKjjlJcyjjFjxx jcyjjFjxx = jcyjjFjxxService.lambdaQuery()
                    .eq(RbtKjjlJcyjjFjxx::getKjjlJcyjjId, tSecretRequest.getJbxxID())
                    .eq(RbtKjjlJcyjjFjxx::getWjlx, "获奖证书")
                    .eq(RbtKjjlJcyjjFjxx::getWjmc, "获奖证书-关键页")
                    .one();
            if (jcyjjFjxx == null) {
                return null;
            }
            FJID = jcyjjFjxx.getFjId();
        } else if (tSecretRequest.getCgjlType() == CgjlType.JSFMJ.getCode()) {
            RbtKjjlJsfmjFjxx jsfmjFjxx = jsfmjFjxxService.lambdaQuery()
                    .eq(RbtKjjlJsfmjFjxx::getKjjlJsfmjId, tSecretRequest.getJbxxID())
                    .eq(RbtKjjlJsfmjFjxx::getWjlx, "获奖证书")
                    .eq(RbtKjjlJsfmjFjxx::getWjmc, "获奖证书-关键页")
                    .one();
            if (jsfmjFjxx == null) {
                return null;
            }
            FJID = jsfmjFjxx.getFjId();
        } else if (tSecretRequest.getCgjlType() == CgjlType.KJJBJ.getCode()) {
            RbtKjjlKjjbjFjxx kjjbjFjxx = kjjbjFjxxService.lambdaQuery()
                    .eq(RbtKjjlKjjbjFjxx::getKjjlKjjbjId, tSecretRequest.getJbxxID())
                    .eq(RbtKjjlKjjbjFjxx::getWjlx, "获奖证书")
                    .eq(RbtKjjlKjjbjFjxx::getWjmc, "获奖证书-关键页")
                    .one();
            if (kjjbjFjxx == null) {
                return null;
            }
            FJID = kjjbjFjxx.getFjId();
        }
        ZtComUploadFile uploadFile = uploadFileService.lambdaQuery()
                .eq(ZtComUploadFile::getId, FJID)
                .one();
        if (uploadFile == null) {
            return null;
        }
        ZtComUploadFileOrigin uploadFileOrigin = uploadFileOriginService.lambdaQuery()
                .eq(ZtComUploadFileOrigin::getId, uploadFile.getFileMd5())
                .one();
        if (uploadFileOrigin == null || uploadFileOrigin.getFilePath().isEmpty()) {
            return null;
        }
        path = uploadFileOrigin.getFilePath();
        if(!ImageExtractionUtil.isImageFile(path,basePath)){
            return null;
        }
        return this.basePath + path;
    }


    public ResponsePicture extractPicture(TSecretRequest tSecretRequest) {
        RequestPicture requestPicture = new RequestPicture();
        requestPicture.setFilePath(tSecretRequest.getFilePath());
        ResponsePicture responsePicture = null;
        try {
            responsePicture = imageExtractionUtil.sendFormPost(requestPicture);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return responsePicture;
    }

    public BaseMatchResult matchProcess(TSecretRequest tSecretRequest) {
        //首先处理附件截图部分的具体地址信息：
        String tSecretPath = getTSecretPath(tSecretRequest);
//        System.out.println("tSecretPath = " + tSecretPath);
        tSecretRequest.setFilePath(tSecretPath);
//        tSecretRequest.setFilePath("/root/OCR_Application/ocr_test_images/test2.png");//测试用路径
//        tSecretRequest.setFilePath("/home/user/workspace/test2.png");//测试时用路径
        BaseMatchResult result = new BaseMatchResult();
        List<String> failReason = new ArrayList<>();
        LocalDateTime xmBeginTimeEnroll = tSecretRequest.getXmBeginTime();
        LocalDateTime xmEndTimeEnroll = tSecretRequest.getXmEndTime();
        ExtractTSecret extractTSecret = null;
        List<String> qlrList  = null;
        if(tSecretPath!=null) {
            ResponsePicture responsePicture = extractPicture(tSecretRequest);
            if(responsePicture!= null) {
                tSecretRequest.setPlainText(responsePicture.getData());
            }
            if(tSecretRequest.getPlainText()!=null) {
                extractTSecret = processTSecret(tSecretRequest.getPlainText());
                if(extractTSecret!=null && extractTSecret.getQlr()!=null && !extractTSecret.getQlr().isEmpty()) {
                    qlrList = extractTSecret.getQlr();
                    tSecretRequest.setQlr(qlrList);
                }
                if(extractTSecret!=null && extractTSecret.getPzrq()!=null) {
                    tSecretRequest.setPzrq(extractTSecret.getPzrq());
                }
            }
        }else {
            failReason.add("获奖证书-关键页图片不存在请重新上传");
        }
        boolean dateMatch = false;
        boolean wcrMatch = false;
        if(tSecretPath!=null && tSecretRequest.getPzrq()!=null) {
            dateMatch = dateMatch(xmBeginTimeEnroll, xmEndTimeEnroll, tSecretRequest);
        }
        if(tSecretPath!=null && qlrList!=null && !qlrList.isEmpty()) {
            wcrMatch = wcrMatch(qlrList, tSecretRequest);
        }
        List<String> fjCheckFailReasons = FJCheck(tSecretRequest);

        if (tSecretPath!=null && tSecretRequest.getPzrq()!=null && !dateMatch) {
            failReason.add("时间不匹配： " + tSecretRequest.getPzrq().format(DATE_FORMAT) + " 技术秘密申请时间并未在项目起始时间段内");
        }
        if (tSecretPath!=null && qlrList!=null && !qlrList.isEmpty() && !wcrMatch) {
            failReason.add("完成人不匹配： " + "项目完成人中的任意一位" + " 并非是专利发明人中的一员");
        }
        if (!fjCheckFailReasons.isEmpty()) {
            failReason.addAll(fjCheckFailReasons);
        }

        result.setFailReason(failReason);
        return result;
    }

    // 专利附件的审查
    public List<String> FJCheck(TSecretRequest tSecretRequest) {
        List<String> failReason = new ArrayList<>();
        if (tSecretRequest.getCgjlType() == CgjlType.JCYJJ.getCode()) {
            for (RbtScfjMb scfjMb : scfjJcyjjLWMbList) {
                List<RbtKjjlJcyjjFjxx> fjxx = jcyjjFjxxService.lambdaQuery()
                        .eq(RbtKjjlJcyjjFjxx::getKjjlJcyjjId, tSecretRequest.getJbxxID())
                        .eq(RbtKjjlJcyjjFjxx::getWjmc, scfjMb.getWjmc())
                        .eq(RbtKjjlJcyjjFjxx::getWjlx, "获奖证书")
                        .list();
                if (fjxx == null || fjxx.isEmpty()) {
                    failReason.add("获奖证书缺少附件:  " + scfjMb.getWjmc() + " ");
                }
            }
        } else if (tSecretRequest.getCgjlType() == CgjlType.JSFMJ.getCode()) {
            for (RbtScfjMb scfjMb : scfjJsfmjLWMbList) {
                List<RbtKjjlJsfmjFjxx> fjxx = jsfmjFjxxService.lambdaQuery()
                        .eq(RbtKjjlJsfmjFjxx::getKjjlJsfmjId, tSecretRequest.getJbxxID())
                        .eq(RbtKjjlJsfmjFjxx::getWjmc, scfjMb.getWjmc())
                        .eq(RbtKjjlJsfmjFjxx::getWjlx, "获奖证书")
                        .list();
                if (fjxx == null || fjxx.isEmpty()) {
                    failReason.add("获奖证书缺少附件:  " + scfjMb.getWjmc() + " ");
                }
            }
        } else if (tSecretRequest.getCgjlType() == CgjlType.KJJBJ.getCode()) {
            for (RbtScfjMb scfjMb : scfjKjjbjjLWMbList) {
                List<RbtKjjlKjjbjFjxx> fjxx = kjjbjFjxxService.lambdaQuery()
                        .eq(RbtKjjlKjjbjFjxx::getKjjlKjjbjId, tSecretRequest.getJbxxID())
                        .eq(RbtKjjlKjjbjFjxx::getWjmc, scfjMb.getWjmc())
                        .eq(RbtKjjlKjjbjFjxx::getWjlx, "获奖证书")
                        .list();
                if (fjxx == null || fjxx.isEmpty()) {
                    failReason.add("获奖证书缺少附件:  " + scfjMb.getWjmc() + " ");
                }
            }
        }
        return failReason;
    }


    // 验证发明人是否是完成人中的一员：
    public boolean wcrMatch(List<String> qlrList, TSecretRequest tSecretRequest) {
        List<WcryShortXM> wcryShortXMList = wcrReadUtil.getWcryFilterByTypeAndId(tSecretRequest.getCgjlType(), tSecretRequest.getJbxxID());
        if (wcryShortXMList == null || wcryShortXMList.isEmpty()) {
            return false;
        }
        for (String name : qlrList) {
            name = name.replaceAll(" ", "");
            String pinyinName = NameConvertUtil.convertToPinyin(name);
            for (WcryShortXM wcryShortXM : wcryShortXMList) {
                String enrollName = NameConvertUtil.convertToPinyin(wcryShortXM.getXm().replaceAll(" ", ""));
                double similarity = pinyinSimilarity(pinyinName, enrollName);
                if (pinyinName.equals(enrollName) || similarity >= 0.8) {
                    return true;
                }
            }
        }
        return false;
    }

    // 技术秘密申请时间的审查：
    public boolean dateMatch(LocalDateTime begin, LocalDateTime end, TSecretRequest tSecretRequest) {
        LocalDateTime pzrq = tSecretRequest.getPzrq();
        return pzrq.isAfter(begin) && pzrq.isBefore(end);
    }

    public ExtractTSecret processTSecret(String request) {
        request = request.replaceAll(":", "：");
        ExtractTSecret response = new ExtractTSecret();
        //完成人：
        String patternStr = "完成.*人"; // 使用.*代替*作为任意字符序
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(request);
        List<String> wcrList = null;
        if (matcher.find()) {
            int start = matcher.start();
            int indexS = request.indexOf("人：", start) + 2;
            int indexE = request.indexOf("\n", indexS);
            String wcr = request.substring(indexS, indexE);
            String[] wcrSplit = wcr.split("、");
            wcrList = new ArrayList<>();
            for (String s : wcrSplit) {
                wcrList.add(s.trim());
            }
        } else {
            return null;
        }
        //技术名称：
        int jsmcStart;
        int jsmcEnd;
        String jsmcStr = null;
        if(request.indexOf("专有技术名称：")!=-1) {
            jsmcStart = request.indexOf("专有技术名称：") + 7;
            jsmcEnd = request.indexOf("\n", jsmcStart);
            if(jsmcEnd!=-1 && jsmcEnd>jsmcStart) {
                jsmcStr = request.substring(jsmcStart, jsmcEnd).trim();
            }
        }
        //评价批准日期;
        int pzrqStart;
        int pzrqEnd;
        LocalDateTime pzrq =null;
        if(request.indexOf("评价批准日期：")!=-1) {
            pzrqStart = request.indexOf("评价批准日期：") + 7;
            pzrqEnd = request.indexOf("\n", pzrqStart);
            if(pzrqEnd!=-1 && pzrqEnd>pzrqStart) {
                pzrq = DateFormatterUtil.StrToLocalDateTime(request.substring(pzrqStart, pzrqEnd));
            }
        }
        response.setQlr(wcrList);
        response.setMc(jsmcStr);
        response.setPzrq(pzrq);
        return response;
    }

//    public static void main(String[] args) {
//        String request = "A\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "EA\n" +
//                "专有技术证书\n" +
//                "A\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "专有技术名称：大宁-吉县区块深层煤层气勘探选区评价技术\n" +
//                "专有技术编号：核协专字[2022]第015号\n" +
//                "CNEA\n" +
//                "专有技术等级：一般\n" +
//                "CNE\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "完成单位：中联煤层气国家工程研究中心有限责任公司\n" +
//                "A\n" +
//                "完成C人：李翔、张雷、侯伟、李永满、李星涛、王安生、李炜静\n" +
//                "评价机构：中国核能行业协会\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "评价批准日期：2022年12月26日\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "本专有技术依据（中国核能行业协会专有技术评价管理办法（试行））\n" +
//                "评价批准之日起生效，有效期五年。\n" +
//                "CNEA\n" +
//                "CNEA\n" +
//                "能行\n" +
//                "发证编号：2022015\n" +
//                "CNEA";
//
//        ExtractTSecret tSecret = new TSecretProcessUtil().processTSecret(request);
//        System.out.println(tSecret);
//    }
}
